****** Chloropleth map for #new GP per county
cap log close
clear all
set more off
set matsize 11000
set maxvar 120000

set scheme s1mono
*Main data pathway globals, set directory to clean data folder
global tables "S:\Project\DemoSos2\common\felles\JR_RG\DrVA\ResultsRev\"
global results "S:\Project\DemoSos2\common\felles\JR_RG\DrVA\ResultsRev\"
global cleandata "S:\Project\DemoSos2\common\felles\JR_RG\DrVA\CleanData\"


cd "$cleandata"
use  clean_patientlevel_file3.dta, clear
keep if yr_str_exog_swap<=2014 ///  clean_patientlevel_file3.dta - includes exog swaps up to 2018 

keep if str_exogGPIDnew!=. & yr_str_exog_swap >= 2005

* largest mobility group 
a2group, individual(str_exogGPIDnew) unit(str_exogGPIDprev) groupvar(pair)
bys pair: ge size_pair = _N
drop if size_pair < 10 ///largest mobility group has 99%


merge m:1 str_exogGPIDnew lopenr  using "S:\Project\DemoSos2\common\felles\JR_RG\DrVA\ResultsJuly2022\/fe_addon_lo2.dta"
drop _merge


bys str_exogGPIDnew: ge n = _n
* recode main VA measure (more VA - better doc, less mortality) 
ge newva = -lofe_death2_55
local va "newva" 
su `va', d
gen stdva = (`va'-r(mean))/r(sd)
local va "stdva"
lab var stdva "Standardized VA"

keep if str_exogGPIDnew!=. & stdva!=. & str_exog_age>= 55
save MapData.dta, replace


*Keep unique new GP and county, create map
use MapData, clear
keep str_exog_muni str_exogGPIDnew	
ge fylkesnumm =floor(str_exog_muni/100)
gen count=1
collapse (max) count, by(fylkesnumm str_exogGPIDnew)
collapse (count) count, by(fylkesnumm)
*gen _ID = county

*Create dta file from shapefile 
*	(kartkatalog.geonorge.no/metadata/adminstrative-enheter-historiske-verjoner/9bc064e3-6c34-4c3a-8421-00290052e9c0)
spshape2dta "AdmEnheter-Norge_fylker_jan2010\polygons-polygon", replace saving(Norway)
merge 1:m fylkesnumm using "Norway.dta", keepusing(_ID)
*Create map
spmap count using Norway_shp, id(_ID) legend(size(large) pos(3))
graph export "$tables/NewGPsPerCounty.png", replace
